<%@ page import="java.sql.ResultSet" %><%--
  Created by IntelliJ IDEA.
  User: lishunlin110
  Date: 2021/6/30
  Time: 9:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <style type="text/css">
        body, html, #allmap {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
            font-family: "微软雅黑";
        }

        <!--
        鼠标绘制点线面-- >
        dl, dt, dd, ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        p {
            font-size: 12px;
        }

        dt {
            font-size: 14px;
            font-family: "微软雅黑";
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding: 5px 0 5px 5px;
            margin: 5px 0;
        }

        dd {
            padding: 5px 0 0 5px;
        }

        li {
            line-height: 28px;
        }

        #r-result {
            width: 100%;
            font-size: 14px;
        }
    </style>
    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=rpFuOrGg4vSclTlBV0yTzBhySbG1sqEn"></script>
    <!--<script type="text/javascript" src="http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"></script>-->
    <!--<script type="text/javascript" src="http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js"></script>&lt;!&ndash;&ndash;&gt;-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/RectangleZoom/1.2/src/RectangleZoom_min.js"></script><!--划区域缩放-->
    <!--加载鼠标绘制工具-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css"/>
    <!--加载检索信息窗口-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css"/>
    <!-- 判定点是否在给定范围内-->
    <script type="text/javascript" src="GeoUtils.js"></script>
    <title>设置点的新图标，点聚合</title>
</head>
<body>
<div id="allmap"></div>
<!--<div id="r-result" style="display: inline-block;width:10%;position: absolute;top:10px;left:100px;">-->
<!--<input id="cityName" type="text" style="width:100px; margin-right:10px;" />-->
<!--<input type="button" value="查询" οnclick="theLocation()" />-->
<!--</div>-->
<div id="r-result" style="display: inline-block;width:12%;position: absolute;top:10px;left:100px;">

    <label>
        <select id="select" onchange="onChange()">
            <option value ="-1">==行政区==</option>
            <option value ="0">蔡甸区</option>
            <option value="1">东西湖区</option>
            <option value="2">汉南区</option>
            <option value="3">汉阳区</option>
            <option value="4">洪山区</option>
            <option value="5">黄陂区</option>
            <option value="6">江岸区</option>
            <option value="7">江汉区</option>
            <option value="8">江夏区</option>
            <option value="9">硚口区</option>
            <option value="10">青山区</option>
            <option value="11">武昌区</option>
            <option value="12">新洲区</option>
        </select>
    </label>
    <input type="text" id="suggestId" size="20" value="百度" placeholder="请输入.." style="width:150px;height:20px;"/>
    <input type="button" onclick="getBoundary()" value="获取轮廓线">
</div>
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
</body>
</html>
<script type="text/javascript">
    // 百度地图API功能
    var map = new BMap.Map("allmap");
    var point = new BMap.Point(114.31, 30.52);
    map.centerAndZoom(point, 15);
    map.enableScrollWheelZoom();
    //
    map.addControl(new BMap.MapTypeControl());   //添加地图类型控件(矢量图、卫星图、三维图)
    map.setCurrentCity("武汉");          // 设置地图显示的城市 此项是必须设置的

    //获取点击点的经纬度,逆地址解析

    var geoc = new BMap.Geocoder();
    map.addEventListener("click", function (e) {
        var pt = e.point;
        geoc.getLocation(pt, function(rs){
            console.info(rs)
            var addComp = rs.addressComponents;
            console.info("经纬度:(" + e.point.lng + "," + e.point.lat+");  "+addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
    });


    //根据地名定位（1）

    function theLocation() {
        //var city = document.getElementById("cityName").value;
        var city = document.getElementById("suggestId").value;
        if (city != "") {
            map.centerAndZoom(city, 11);      // 用城市名设置地图中心点
        }
    }
    //根据输入查找定位（2）
    //
    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
        {
            "input": "suggestId"
            , "location": map
        });

    ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        document.getElementById("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        document.getElementById("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });

    function setPlace() {
        map.clearOverlays();    //清除地图上所有覆盖物
        function myFun() {
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 18);
            map.addOverlay(new BMap.Marker(pp));    //添加标注
        }

        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        local.search(myValue);
    }


    //修改图标
    //
    var pt = new BMap.Point(116.417, 39.909);
    var img = "pic.png";
    var myIcon = new BMap.Icon(img, new BMap.Size(300, 157));
    var marker2 = new BMap.Marker(pt, {icon: myIcon});  // 创建标注
    map.addOverlay(marker2);              // 将标注添加到地图中
    var record = [];
    marker2.addEventListener('click',function () {
        //点击标注时切换标注，同时记录标注内容；再次点击标注时换回原来标注，并将该标注内容从记录中去除
        if(img == "pic.png"){
            record.push(this);
        }else{
            for(var i in record){
                if(record[i] == this){
                    record.splice(i,1)
                }
            }
        }
        img = img=="pic.png"?"video.png":"pic.png";
        this.setIcon(new BMap.Icon(img,new BMap.Size(300, 157)));

        console.info(record)
    })

    //区县级别的信息mBaiduMap.getMapStatus().zoom

    var data_district = [[116.395736, 39.921032, "地址：北京市西城区西华门大街"],
        [116.386968, 39.16799, "地址：北京市西城区北安里1号"],
        [116.382405, 39.92117, "地址：北京市西城区灵境胡同73号"]
    ];

    //给点添加信息窗口
    //
    var data_info = [["北京市", "地址：shenynnnn"],
        [116.406605, 39.921585, "地址：北京市东城区东华门大街"],
        [116.449713, 39.926498, "地址：北京市朝阳区区委"]
    ];
    var community =[];
    <%ResultSet rs =(ResultSet)request.getAttribute("communities");
    if(rs!=null){
        try{
            int i=0;
            while (rs.next())
            {%>
            var j=<%=i%>;
            var lng=<%=rs.getString("longitude")%>;
            var lat=<%=rs.getString("latitude")%>;
            var name="<%=rs.getString("name")%>";
            var adm="<%=rs.getString("adm_region")%>";

             community[j]=[lng,lat,name,adm];


 <%
            i++;
            }


        }catch (Exception e){

            e.printStackTrace();
        }}
 %>


        var opts = {
            width: 250,     // 信息窗口宽度
            height: 80,     // 信息窗口高度
            title: "小区名:", // 信息窗口标题
            enableMessage: true//设置允许信息窗发送短息
        };


    function  onChange(){

        map.clearOverlays();        //清除地图覆盖物
        var elementById = document.getElementById("select");
        var index =elementById.selectedIndex;
        var adm = elementById.options[index].text;
        //alert(adm);

        for (var x = 0; x < community.length; x++) {

            //alert(community[x][3]);
            if(adm===community[x][3]){
                // alert(adm+"  "+community[x][3]);
                // alert(community[x][0]+"  "+community[x][1]);
                var Icon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                    offset: new BMap.Size(10, 25), // 指定定位位置
                    imageOffset: new BMap.Size(0, 0- 12 * 25) // 设置图片偏移使用左侧的图片
                    //  imageOffset: new BMap.Size(-20, 0 - 10 * 25) // 设置图片偏移使用右侧的图片0-x*25代表使用第x+1张图片
                });
                var marker2 = new BMap.Marker(new BMap.Point(community[x][0],community[x][1]),{icon: Icon});  // 创建标注
                var content2 = community[x][2];
                map.addOverlay(marker2);// 将标注添加到地图中
                addClickHandler(content2, marker2);
            }
        }
        getBoundary(adm);

    }



    function addClickHandler(content, marker) {
        var rightFlag = true;
        marker.addEventListener("mouseover", function (e) {
                openInfo(content, e)
            }
        );
        marker.addEventListener("click",function (e) {
            map.centerAndZoom(e.point, 18);
            var pt = e.point;
            geoc.getLocation(pt, function(rs){
                var addComp = rs.addressComponents;
                console.info(rs)
                console.info(addComp)
                console.info("经纬度:(" + e.point.lng + "," + e.point.lat+"); "+addComp.province + "," + addComp.city + "," + addComp.district + "," + addComp.street + "," + addComp.streetNumber);
                if(rightFlag){
                    getBoundary(addComp.district);
                    rightFlag = false;
                }else{
                    getBoundary((addComp.city));
                    rightFlag = true;
                }
            });
        })
    }
    function openInfo(content, e) {
        var p = e.target;
        var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        var infoWindow = new BMap.InfoWindow(content, opts);  // 创建信息窗口对象
        map.openInfoWindow(infoWindow, point); //开启信息窗口
    }

    //鼠标拉框放大地图
    ///
    var myDrag = new BMapLib.RectangleZoom(map, {
        followText: "拖拽鼠标进行操作"
    });
    //myDrag.open();  //开启拉框放大
    myDrag.close();  //关闭拉框放大

    //鼠标绘制点线面工具栏(每次绘制前将出marker之外的覆盖层都清除)
    ///
    var overlays = [];
    var overlaycomplete = function (e) {
        if(overlays != null){
            //删除前一个绘制的覆盖层，始终只显示最新绘制的一个覆盖层
            map.removeOverlay(overlays[0])
            overlays.splice(0,1);
        }
        overlays.push(e.overlay);
        if (e.drawingMode == BMAP_DRAWING_CIRCLE) {
            //覆盖层为圆，获取画圆的圆心点和所画圆的半径，在圆范围内查找
            localSearch.searchNearby('银行', new BMap.Point(e.overlay.getCenter().lng, e.overlay.getCenter().lat), e.overlay.getRadius());
        } else if (e.drawingMode == BMAP_DRAWING_RECTANGLE) {
            //覆盖层为矩形，获取到绘制矩形的起点(左下角)与结束点（右上角）的坐标,根据坐标建立查找范围
            var pStart = new BMap.Point(e.overlay.getPath()[3].lng, e.overlay.getPath()[3].lat);
            var pEnd = new BMap.Point(e.overlay.getPath()[1].lng, e.overlay.getPath()[1].lat);
            localSearch.searchInBounds("银行", new BMap.Bounds(pStart, pEnd));
        } else if (e.drawingMode == BMAP_DRAWING_POLYGON) {
            //覆盖层为多边形,判断预设的点是否在多边形范围内
            if (BMapLib.GeoUtils.isPointInPolygon(new BMap.Point(116.412222, 39.912345), e.overlay)) {
                alert("该point 在多边形范围内");
            } else {
                alert("该point 不在多边形范围内");
            }
        }
    };
    var styleOptions = {
        strokeColor: "red",    //边线颜色。
        fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,       //边线透明度，取值范围0 - 1。
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }
    //实例化鼠标绘制工具
    var drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(150, 5), //偏离值
            drawingModes: [BMAP_DRAWING_CIRCLE, BMAP_DRAWING_POLYGON, BMAP_DRAWING_RECTANGLE]//工具栏上出现的绘制内容，以数组方式传入
        },
        circleOptions: styleOptions, //圆的样式
        polygonOptions: styleOptions, //多边形的样式
        rectangleOptions: styleOptions //矩形的样式
    });
    //添加鼠标绘制工具监听事件，用于获取绘制结果
    //    drawingManager.addEventListener('click',map.clearOverlays())
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);

    //平移和缩放按钮

    var top_left_navigation = new BMap.NavigationControl({
        anchor: BMAP_ANCHOR_TOP_LEFT,
        type: BMAP_NAVIGATION_CONTROL_SMALL
    });//平移缩放按钮
    /*缩放控件type有四种类型:
     BMAP_NAVIGATION_CONTROL_SMALL：仅包含平移和缩放按钮；BMAP_NAVIGATION_CONTROL_PAN:仅包含平移按钮；BMAP_NAVIGATION_CONTROL_ZOOM：仅包含缩放按钮*/
    map.addControl(top_left_navigation);


    //查找指定内容
    ///
    var localSearch = new BMap.LocalSearch(map, {
        renderOptions: {
            map: map
        },
        onSearchComplete: function (results) {
            alert('drawing finished，start search...');
        }
    });

    //行政区域边界绘制

    function getBoundary(name){
        if(name == null)
            name = document.getElementById("suggestId").value;
        var bdary = new BMap.Boundary();
        console.info(name)
        bdary.get(name, function(rs){       //获取行政区域
            var count = rs.boundaries.length; //行政区域的点有多少个
            for(var i = 0; i < count; i++){
                var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
                map.addOverlay(ply);  //添加覆盖物
                map.setViewport(ply.getPath());    //调整视野
            }
        });
    }

</script>
